package com.zmm.book.keep.interceptor;

import com.zmm.common.base.model.Result;
import com.zmm.common.base.model.ResultCode;
import com.zmm.common.constant.Constant;
import com.zmm.util.auth.constant.AuthConstant;
import com.zmm.util.auth.interceptor.AbstractAuthInterceptor;
import com.zmm.util.auth.interceptor.InterceptorHandlerUtil;
import com.zmm.util.auth.model.AuthParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 900045
 * @description:
 * @name BookKeepAuthInterceptor
 * @date By 2021-09-28 10:24:34
 */
@Slf4j
@Component
public class BookKeepAuthInterceptor extends AbstractAuthInterceptor implements HandlerInterceptor {


	@Value("${spring.application.name}")
	private String serviceName;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
							 Object handler) throws Exception {
		this.doClean();

		String url = request.getRequestURI();
		// 健康检查
		if (url.endsWith(Constant.CHECKUP)) {
			checkResp(response,serviceName);
			return false;
		}
		// 指定路径放行 首页接口放行
		/**
		 *
		 String requestURI = request.getRequestURI()
		 AntPathMatcher antPathMatcher = new AntPathMatcher()
		 boolean match1 = antPathMatcher.match("/home/page", requestURI)

		 boolean match2 = antPathMatcher.match("/find/article/articleIds", requestURI)
		 if (match1 || match2 ){
		 return HandlerInterceptor.super.preHandle(request, response, handler)
		 }
		 */

		//从请求头中获取 token字符串，
		String token = request.getHeader(AuthConstant.HEADER_TOKEN_KEY);
		AuthParam param = InterceptorHandlerUtil.preHandle(request, response);
		if (StringUtils.isBlank(token)) {
			// return false
			// return returnResp(response, Result.error(ResultCode.NOT_LOGGED))
			boolean flag = doPreHandle(param, handler);
			if (flag) {
				return HandlerInterceptor.super.preHandle(request, response, handler);
			} else {
				return returnResp(response, Result.error(ResultCode.NOT_LOGGED));
			}
		}
		
		boolean flag = doPreHandle(param, handler);
		if (flag) {
			return HandlerInterceptor.super.preHandle(request, response, handler);
		}
		return false;
	}

	// 取消 afterCompletion 事件
}
